﻿using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using TemplateGenerator.Entities;
using TemplateGenerator.Logic;

namespace TemplateGenerator.Controls {
	/// <summary>
	/// Interaction logic for TemplateOverview.xaml
	/// </summary>
	public partial class TemplateOverview : Window {

		public ObservableCollection<CustomTemplate> TemplateCollection { get; set; }
		
		public TemplateOverview() {
			InitializeComponent();

            //set datacontext to the template list generated at startup
            dtgTemplates.DataContext = GeneratorHandler.CustomTemplates;
		}

		private void ButtonDeleteClick(object sender, RoutedEventArgs e) {
			e.Handled = true;

            //gets button pressed and puts the datacontext in a custom template instance
			var template = ((Button)sender).DataContext as CustomTemplate;
			if (template == null) return;

            //ask users confirmation for file deletion
			if (!Communication.ConfirmAction("Are you sure you want to delete " + template.Name + "?")) return;

            //delete's file
            if (!GeneratorHandler.DeleteFile(template.FilePath)) return;

            //reloads the template lists and updates the datagrid with new list
            GeneratorHandler.LoadTemplates();
          //  dtgTemplates.DataContext = GeneratorHandler.CustomTemplates;
		}

        private void FileDropHandler(object sender, DragEventArgs e)
        {
            //checks if the item dropped is a file
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
            	//gets file dropped
            	var strings = e.Data.GetData(DataFormats.FileDrop, true) as string[];
            	if (strings != null)
            	{
            		FileInfo file = new FileInfo(strings[0]);

            		//checks if file is a .dotx template
            		if (file.Extension == ".dotx")
            		{
            			//copies the dropped file to the resource map
            			GeneratorHandler.CopyFile(file.FullName);

            			//reloads the template lists and updates the datagrid with new list
            			GeneratorHandler.LoadTemplates();
          //  			dtgTemplates.DataContext = GeneratorHandler.CustomTemplates;
            		}
            		else
            		{
            			//warn users that only .dotx files can be added
            			Communication.Notify("Only .dotx files can be added", "Error");
            		}
            	}
            }
        	e.Handled = true;
        }
	}
}
